<?php

namespace Upfor\UpforPHP\Library;

class Password {

    protected static $algorithm = PASSWORD_BCRYPT;

    /**
     * Default computing options
     *
     * @var array
     */
    protected static $options = ['cost' => 8];

    /**
     * Returns a password hash.
     *
     * @access public
     * @param  string     $password Password
     * @param  null|array $options  Computing options
     * @return string
     */
    public static function hash($password) {
        return password_hash($password, self::$algorithm, self::$options);
    }

    /**
     * Checks if the password needs to be rehashed.
     *
     * @access public
     * @param  string $hash Password hash to check
     * @return boolean
     */
    public static function needsRehash($hash) {
        return password_needs_rehash($hash, self::$algorithm, self::$options);
    }

    /**
     * Validates a password hash.
     *
     * @param  string $password Password
     * @param  string $hash     Password hash
     * @return boolean
     */
    public static function validate($password, $hash) {
        return password_verify($password, $hash);
    }

    /**
     * Generate random password
     *
     * @param  integer $length
     * @return string
     */
    public static function randomPassword($length = 8) {
        // Password chars
        $chars = array(
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
            'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
            'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
            '-', '_', '[', ']', '{', '}', '<', '>', '~', '`', '+', '=',
            ',', '.', ';', ':', '/', '?', '|',
        );

        $keys = array_rand($chars, $length);

        $password = '';
        foreach ($keys as $key) {
            $password .= $chars[$key];
        }

        return $password;
    }

}
